﻿using System;
using System.Windows.Forms;
using Library.File;
using System.Drawing;
using MySql.Data.MySqlClient;
using System.Data;

namespace FisplayTools
{
    public partial class mainForm : Form
    {
        public mainForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 开始运行
        /// </summary>
        public void formStart()
        {
            try
            {
                //打开程序时读取ini中的参数并显示
                string stringFileTempPath = Application.ExecutablePath.ToLower(); //把程序主路径改为小写
                string realIniPath = stringFileTempPath.Replace("fisplaytools.exe", "config.ini");
                //MessageBox.Show(realIniPath); //调试代码
                Ini ini = new Ini(realIniPath);
                if (ini.ReadValue("sql_config", "address") != "")
                {
                    sqlServerAddText.Text = ini.ReadValue("sql_config", "address");
                    sqlUsernameText.Text = ini.ReadValue("sql_config", "username");
                    sqlPasswordText.Text = ini.ReadValue("sql_config", "password");
                    sqlDbText.Text = ini.ReadValue("sql_config", "database");
                    sqlCharsetText.Text = ini.ReadValue("sql_config", "charset");
                    statusText.ForeColor = Color.Black;
                    statusText.Text = "配置文件读取正常";
                }
                else
                {
                    statusText.ForeColor = Color.Red;
                    statusText.Text = "无法找到ini配置，请检查ini配置文件";
                    foreach (Control tControl in tabControl.Controls)
                    {
                        tControl.Enabled = false;
                    }
                    sqlconMenuStrip.Enabled = false;
                    sqldisconMenuStrip.Enabled = false;
                }
            }
            catch
            {
                sqlconMenuStrip.Enabled = false;
                statusText.ForeColor = Color.Red;
                statusText.Text = "无法初始化参数";
            }
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        public void queryData()
        {
            string sqlstr = "select * from details";        //从sql读取语句
            MySqlCommand cmd = new MySqlCommand(sqlstr, con);       //整合sql命令
            MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            adapter.Fill(ds);       //数据填充至ds    
            dataGridView1.DataSource = ds.Tables[0];
            for (int i = 0; i < dataGridView1.RowCount; i++)
            {
                dataGridView1.Rows[i].Cells[11].Value = ds.Tables[0].Rows[i]["状态"];
            }
        }

        /// <summary>
        /// 查询栏位
        /// </summary>
        public void readColumn()
        {
            string sqlstr = "select COLUMN_NAME from information_schema.COLUMNS where table_name = 'details';";
            MySqlCommand cmd = new MySqlCommand(sqlstr, con);
            MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            adapter.Fill(ds);
            DataTable dt = ds.Tables[0];
            string[] strings = new string[11]; //连id，一共11个栏位
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                strings[i] = dt.Rows[i]["COLUMN_NAME"].ToString();
            }
            columnLabel1.Text = columnSettingText1.Text = strings[1];
            columnLabel2.Text = columnSettingText2.Text = strings[2];
            columnLabel3.Text = columnSettingText3.Text = strings[3];
            columnLabel4.Text = columnSettingText4.Text = strings[4];
            columnLabel5.Text = columnSettingText5.Text = strings[5];
            columnLabel6.Text = columnSettingText6.Text = strings[6];
            columnLabel7.Text = columnSettingText7.Text = strings[7];
            columnLabel8.Text = columnSettingText8.Text = strings[8];
            columnLabel9.Text = columnSettingText9.Text = strings[9];
            columnLabel10.Text = columnSettingText10.Text;
        }

        public void clearAddText()
        {
            columnText1.Clear();
            columnText2.Clear();
            columnText3.Clear();
            columnText4.Clear();
            columnText5.Clear();
            columnText6.Clear();
            columnText7.Clear();
            columnText8.Clear();
            columnText9.Clear();
        }

        private void mainForm_Load(object sender, EventArgs e)
        {
            formStart();
        }


        static MySqlConnection con; //将数据库连接变量作为全局，便于随时close
        static MySqlCommand mysqlcmd;
        private void sqlconMenuStrip_Click(object sender, EventArgs e)
        {
            try
            {
                statusText.Text = "正在连接数据库……请耐心等待";
                string constr = "server='" + sqlServerAddText.Text + "';User Id='" + sqlUsernameText.Text + "';password='" + sqlPasswordText.Text + "';Database='" + sqlDbText.Text + "';Charset='" + sqlCharsetText.Text + "';";
                con = new MySqlConnection(constr);
                con.Open();
                string sqlstr = "select * from display_settings";
                MySqlCommand cmd = new MySqlCommand(sqlstr, con);
                MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adapter.Fill(ds);
                DataTable dt = ds.Tables[0];
                delayRefreshText.Text = dt.Rows[0]["setting_value"].ToString();
                webTitleText.Text = dt.Rows[1]["setting_value"].ToString();
                sqlconMenuStrip.Enabled = false;
                statusText.Text = "数据库连接成功！";
                sqldisconMenuStrip.Enabled = true;  //断开数据库按钮 生效
                reiniMenuStrip.Enabled = false;     //刷新配置参数按钮 禁用
                readColumn();
                foreach (Control tControl in tabControl.Controls)
                {
                    if (tControl is TabPage)
                    {
                        foreach (Control gControl in tControl.Controls)
                        {
                            if (gControl.Enabled == false)
                            {
                                gControl.Enabled = true;
                            }
                            if (gControl is GroupBox)
                            {
                                foreach (Control subControl in gControl.Controls)
                                {
                                    if (subControl is Button && subControl.Text == "编辑配置")
                                    {
                                        subControl.Enabled = true;
                                    }
                                }
                            }
                        }
                    }
                }
                columnLabel10.Enabled = false;
                columnText10.Enabled = false;
                columnSettingType1.SelectedIndex = 0;
                columnSettingType2.SelectedIndex = 0;
                columnSettingType3.SelectedIndex = 0;
                columnSettingType4.SelectedIndex = 0;
                columnSettingType5.SelectedIndex = 0;
                columnSettingType6.SelectedIndex = 0;
                columnSettingType7.SelectedIndex = 0;
                columnSettingType8.SelectedIndex = 0;
                columnSettingType9.SelectedIndex = 0;
                columnSettingType10.SelectedIndex = 0;

                sqlstr = "select * from details";        //从sql读取语句
                cmd = new MySqlCommand(sqlstr, con);       //整合sql命令
                adapter = new MySqlDataAdapter(cmd);
                ds = new DataSet();
                adapter.Fill(ds);       //数据填充至ds
                dt = ds.Tables[0];
                dataGridView1.ReadOnly = true;
                dataGridView1.DataSource = ds.Tables[0];
                dataGridView1.Columns[0].Width = 50;
                DataGridViewButtonColumn btnColumn = new DataGridViewButtonColumn();
                btnColumn.Name = "动作";
                btnColumn.UseColumnTextForButtonValue = false;
                if (dataGridView1.ColumnCount < 12)
                {
                    dataGridView1.Columns.Add(btnColumn);           //将新增的一列添加至dataGridView1中
                    dataGridView1.Columns[11].DisplayIndex = 0;     //将新增的一列移动至第一列（视觉上）
                    dataGridView1.Columns[11].Frozen = true;
                    dataGridView1.Columns[11].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;  //将新增的一列冻结
                }
                for (int i = 0; i < dataGridView1.RowCount; i++)
                {
                    dataGridView1.Rows[i].Cells[11].Value = dt.Rows[i]["状态"].ToString();
                    if (dataGridView1.Rows[i].Cells[11].Value.ToString() == "待维修")
                    {
                        dataGridView1.Rows[i].Cells[11].Value = "待维修";
                    }
                    else if (dataGridView1.Rows[i].Cells[11].Value.ToString() == "维修中")
                    {
                        dataGridView1.Rows[i].Cells[11].Value = "维修中";
                    }
                    else if (dataGridView1.Rows[i].Cells[11].Value.ToString() == "待领取")
                    {
                        dataGridView1.Rows[i].Cells[11].Value = "待领取";
                    }
                    else
                    {
                        dataGridView1.Rows[i].Cells[11].Value = "已结案";
                    }
                }

            }
            catch (Exception ex)
            {
                statusText.ForeColor = Color.Red;
                statusText.Text = "无法连接到数据库！";
                MessageBox.Show("无法连接到数据库！");
            }
        }

        private void sqldisconMenuStrip_Click(object sender, EventArgs e)
        {
            con.Close();
            statusText.Text = "数据库已断开！";
            sqldisconMenuStrip.Enabled = false;
            sqlconMenuStrip.Enabled = true;
            reiniMenuStrip.Enabled = true;     //刷新配置参数按钮 启用
            foreach (Control tControl in tabControl.Controls)
            {
                tControl.Enabled = false;
            }
            MessageBox.Show("数据库连接已关闭，现在将退出程序！");
            Close();
        }

        private void reiniMenuStrip_Click(object sender, EventArgs e)
        {
            formStart();
            if (statusText.Text == "无法找到ini配置，请检查ini配置文件" || statusText.Text == "无法初始化参数")
            {
                sqlconMenuStrip.Enabled = false;
                sqldisconMenuStrip.Enabled = false;
            }
            else
            {
                sqlconMenuStrip.Enabled = true;
            }

        }

        private void refreshData_Click(object sender, EventArgs e)
        {
            queryData();
            statusText.Text = "查询/刷新成功";
        }

        private void clearAll_Click(object sender, EventArgs e)
        {
            clearAddText();
        }

        private void saveSqlSettings_Click(object sender, EventArgs e)
        {
            string stringFileTempPath = Application.ExecutablePath.ToLower(); //把程序主路径改为小写
            string realIniPath = stringFileTempPath.Replace("fisplaytools.exe", "config.ini");
            Ini ini = new Ini(realIniPath);
            if (ini.ReadValue("sql_config", "address") != "")
            {
                ini.Writue("sql_config", "address", sqlServerAddText.Text);
                ini.Writue("sql_config", "username", sqlUsernameText.Text);
                ini.Writue("sql_config", "password", sqlPasswordText.Text);
                ini.Writue("sql_config", "database", sqlDbText.Text);
                ini.Writue("sql_config", "charset", sqlCharsetText.Text);
                sqlServerAddText.Enabled = false;
                sqlUsernameText.Enabled = false;
                sqlPasswordText.Enabled = false;
                sqlDbText.Enabled = false;
                sqlCharsetText.Enabled = false;
                saveSqlSettings.Enabled = false;
                editSqlSettings.Enabled = true;
                MessageBox.Show("强烈建议更新数据库配置后重新启动软件！");
            }
            else
            {
                statusText.ForeColor = Color.Red;
                statusText.Text = "配置文件错误，请检查配置文件！";
            }
        }

        private void editSqlSettings_Click(object sender, EventArgs e)
        {
            sqlServerAddText.Enabled = true;
            sqlUsernameText.Enabled = true;
            sqlPasswordText.Enabled = true;
            sqlDbText.Enabled = true;
            sqlCharsetText.Enabled = true;
            saveSqlSettings.Enabled = true;
            editSqlSettings.Enabled = false;
        }

        private void saveDisplaySettings_Click(object sender, EventArgs e)
        {
            string sqlstr = "UPDATE display_settings SET setting_value='" + delayRefreshText.Text + "' where setting_name='delay_refresh_time'";
            MySqlCommand cmd = new MySqlCommand(sqlstr, con);
            cmd.ExecuteNonQuery();
            sqlstr = "UPDATE display_settings SET setting_value='" + webTitleText.Text + "' where setting_name='web_title'";
            cmd = new MySqlCommand(sqlstr, con);
            cmd.ExecuteNonQuery();
            delayRefreshText.Enabled = false;
            webTitleText.Enabled = false;
            saveDisplaySettings.Enabled = false;
            editDisplaySettings.Enabled = true;
        }

        private void editDisplaySettings_Click(object sender, EventArgs e)
        {
            delayRefreshText.Enabled = true;
            webTitleText.Enabled = true;
            editDisplaySettings.Enabled = false;
            saveDisplaySettings.Enabled = true;
        }

        private void saveColumnSettings_Click(object sender, EventArgs e)
        {
            string sqlstr = "ALTER TABLE details CHANGE " + columnLabel1.Text + " " + columnSettingText1.Text + " " + columnSettingType1.Text + "(255) NOT NULL";
            MySqlCommand cmd = new MySqlCommand(sqlstr, con);
            cmd.ExecuteNonQuery();
            sqlstr = "ALTER TABLE details CHANGE " + columnLabel2.Text + " " + columnSettingText2.Text + " " + columnSettingType2.Text + "(255) NOT NULL";
            cmd = new MySqlCommand(sqlstr, con);
            cmd.ExecuteNonQuery();
            sqlstr = "ALTER TABLE details CHANGE " + columnLabel3.Text + " " + columnSettingText3.Text + " " + columnSettingType3.Text + "(255) NOT NULL";
            cmd = new MySqlCommand(sqlstr, con);
            cmd.ExecuteNonQuery();
            sqlstr = "ALTER TABLE details CHANGE " + columnLabel4.Text + " " + columnSettingText4.Text + " " + columnSettingType4.Text + "(255) NOT NULL";
            cmd = new MySqlCommand(sqlstr, con);
            cmd.ExecuteNonQuery();
            sqlstr = "ALTER TABLE details CHANGE " + columnLabel5.Text + " " + columnSettingText5.Text + " " + columnSettingType5.Text + "(255) NOT NULL";
            cmd = new MySqlCommand(sqlstr, con);
            cmd.ExecuteNonQuery();
            sqlstr = "ALTER TABLE details CHANGE " + columnLabel6.Text + " " + columnSettingText6.Text + " " + columnSettingType6.Text + "(255) NOT NULL";
            cmd = new MySqlCommand(sqlstr, con);
            cmd.ExecuteNonQuery();
            sqlstr = "ALTER TABLE details CHANGE " + columnLabel7.Text + " " + columnSettingText7.Text + " " + columnSettingType7.Text + "(255) NOT NULL";
            cmd = new MySqlCommand(sqlstr, con);
            cmd.ExecuteNonQuery();
            sqlstr = "ALTER TABLE details CHANGE " + columnLabel8.Text + " " + columnSettingText8.Text + " " + columnSettingType8.Text + "(255) NOT NULL";
            cmd = new MySqlCommand(sqlstr, con);
            cmd.ExecuteNonQuery();
            sqlstr = "ALTER TABLE details CHANGE " + columnLabel9.Text + " " + columnSettingText9.Text + " " + columnSettingType9.Text + "(255) NOT NULL";
            cmd = new MySqlCommand(sqlstr, con);
            cmd.ExecuteNonQuery();
            //sqlstr = "ALTER TABLE details CHANGE " + columnLabel10.Text + " " + columnSettingText10.Text + " " + columnSettingType10.Text + "(255) NOT NULL";
            //cmd = new MySqlCommand(sqlstr, con);
            //cmd.ExecuteNonQuery();
            saveColumnSettings.Enabled = false;
            editColumnSettings.Enabled = true;
            columnSettingText1.Enabled = false;
            columnSettingText2.Enabled = false;
            columnSettingText3.Enabled = false;
            columnSettingText4.Enabled = false;
            columnSettingText5.Enabled = false;
            columnSettingText6.Enabled = false;
            columnSettingText7.Enabled = false;
            columnSettingText8.Enabled = false;
            columnSettingText9.Enabled = false;
            columnSettingText10.Enabled = false;
            columnSettingType1.Enabled = false;
            columnSettingType2.Enabled = false;
            columnSettingType3.Enabled = false;
            columnSettingType4.Enabled = false;
            columnSettingType5.Enabled = false;
            columnSettingType6.Enabled = false;
            columnSettingType7.Enabled = false;
            columnSettingType8.Enabled = false;
            columnSettingType9.Enabled = false;
            columnSettingType10.Enabled = false;
            statusText.Text = "保存栏位参数成功";
            readColumn();
        }

        private void editColumnSettings_Click(object sender, EventArgs e)
        {
            columnSettingText1.Enabled = true;
            columnSettingText2.Enabled = true;
            columnSettingText3.Enabled = true;
            columnSettingText4.Enabled = true;
            columnSettingText5.Enabled = true;
            columnSettingText6.Enabled = true;
            columnSettingText7.Enabled = true;
            columnSettingText8.Enabled = true;
            columnSettingText9.Enabled = true;
            columnSettingType1.Enabled = true;
            columnSettingType2.Enabled = true;
            columnSettingType3.Enabled = true;
            columnSettingType4.Enabled = true;
            columnSettingType5.Enabled = true;
            columnSettingType6.Enabled = true;
            columnSettingType7.Enabled = true;
            columnSettingType8.Enabled = true;
            columnSettingType9.Enabled = true;
            saveColumnSettings.Enabled = true;
            editColumnSettings.Enabled = false;
        }

        private void addNew_Click(object sender, EventArgs e)
        {
            string sqlstr = "INSERT into details (id," + columnLabel1.Text + "," + columnLabel2.Text + "," + columnLabel3.Text + "," + columnLabel4.Text + "," + columnLabel5.Text + "," + columnLabel6.Text + "," + columnLabel7.Text + "," + columnLabel8.Text + "," + columnLabel9.Text + "," + columnLabel10.Text + ") VALUES(NULL,'" + columnText1.Text + "','" + columnText2.Text + "','" + columnText3.Text + "','" + columnText4.Text + "','" + columnText5.Text + "','" + columnText6.Text + "','" + columnText7.Text + "','" + columnText8.Text + "','" + columnText9.Text + "','待维修');";
            MySqlCommand cmd = new MySqlCommand(sqlstr, con);
            cmd.ExecuteNonQuery();
            clearAddText();
            //queryData();
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == dataGridView1.Columns[11].Index && e.RowIndex >= 0)
            {
                int _UID = e.RowIndex;
                string s = Convert.ToString(dataGridView1.Rows[_UID].Cells[11].Value).ToString();
                if (s == "待维修")
                {
                    dataGridView1.Rows[_UID].Cells[11].Value = "维修中";
                }
                else if (s == "维修中")
                {
                    dataGridView1.Rows[_UID].Cells[11].Value = "待领取";
                }
                else if (s == "待领取")
                {
                    dataGridView1.Rows[_UID].Cells[11].Value = "已结案";
                }
                else
                {
                    statusText.Text = "case已经结案，无法改变状态！";
                }
            }
        }
    }
}
